<template>
  <div class="dothings-container">
    <!-- 输入区 -->
    <div class="input-area">
      <el-date-picker v-model="date" type="date" size="large" style="width: 180px;" :editable="false"
        placeholder="选择日期" />
      <el-time-picker v-model="time" size="large" style="width: 220px;" placeholder="选择时间" format="HH:mm:ss"
        value-format="HH:mm:ss" />
      <input v-model="thing" placeholder="要做的事情" class="thing-input" />
      <button @click="addThing" class="el-btn">确定</button>
    </div>
    
    <!-- 编辑弹窗 -->
    <el-dialog :visible.sync="editDialogVisible" title="编辑事项">
      <template #content>
        <el-form :model="editForm" label-width="80px">
          <el-form-item label="日期">
            <el-date-picker v-model="editForm.date" type="date" :editable="false" placeholder="选择日期" />
          </el-form-item>
          <el-form-item label="时间">
            <el-time-picker v-model="editForm.time" placeholder="选择时间" format="HH:mm:ss" value-format="HH:mm:ss" />
          </el-form-item>
          <el-form-item label="事项">
            <el-input v-model="editForm.thing" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 展示区 -->
    <div class="display-area">
      <div class="todo-list">
        <h3>今天</h3>
        <div class="empty-list" v-if="todayList.length === 0">暂无待办事项</div>
        <table class="todo-table" v-else>
          <thead>
            <tr>
              <th>时间</th>
              <th>事项</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in todayList" :key="item.id">
              <td>{{ item.date }} {{ item.time }}</td>
              <td>{{ item.thing }}</td>
              <td>
                <el-button :type="item.done ? 'success' : 'warning'" size="small" @click="toggleDone(item)">{{ item.done ? '已做' : '未做' }}</el-button>
              </td>
              <td>
                <el-button type="primary" size="mini" @click="startEdit(item)">修改</el-button>
                <el-button type="danger" size="mini" @click="confirmDelete(item)">删除</el-button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div class="todo-list">
        <h3>以后</h3>
        <div class="empty-list" v-if="futureList.length === 0">暂无待办事项</div>
        <table class="todo-table" v-else>
          <thead>
            <tr>
              <th>时间</th>
              <th>事项</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in futureList" :key="item.id">
              <td>{{ item.date }} {{ item.time }}</td>
              <td>{{ item.thing }}</td>
              <td>
                <el-button :type="item.done ? 'success' : 'warning'" size="small" @click="toggleDone(item)">{{ item.done ? '已做' : '未做' }}</el-button>
              </td>
              <td>
                <el-button type="primary" size="mini" @click="startEdit(item)">修改</el-button>
                <el-button type="danger" size="mini" @click="confirmDelete(item)">删除</el-button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<style scoped>
.dothings-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 32px 0;
}

.input-area {
  display: flex;
  gap: 16px;
  align-items: center;
  margin-bottom: 16px;
}

.thing-input {
  width: 220px;
  padding: 10px;
  font-size: 18px;
}

.el-btn {
  padding: 10px 24px;
  font-size: 18px;
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.display-area {
  display: flex;
  gap: 32px;
  justify-content: center;
}

.todo-list {
  flex: 1;
  background: #f5f5f5;
  border-radius: 8px;
  padding: 16px;
}

.todo-table {
  width: 100%;
  border-collapse: collapse;
}

.todo-table th, .todo-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.todo-table th {
  background-color: #f0f0f0;
  font-weight: bold;
}

.todo-list > h3 {
  text-align: center;
}

.empty-list {
  text-align: center;
  padding: 20px;
  color: #999;
}

@media (max-width: 700px) {
  .input-area {
    flex-direction: column;
    gap: 12px;
  }
  .thing-input {
    width: 100%;
    padding: 10px 12px;
    font-size: 16px;
    border-radius: 8px;
    border: 1px solid #ccc;
    box-sizing: border-box;
  }
  .el-btn {
    width: 100%;
    margin-top: 8px;
    font-size: 16px;
    border-radius: 8px;
  }
  .display-area {
    flex-direction: column;
    gap: 20px;
  }
  .todo-list {
    width: 100%;
  }
  .todo-table th, .todo-table td {
    font-size: 14px;
    padding: 6px;
  }
  .todo-table th {
    font-weight: 600;
  }
}

.el-time-panel {
  max-height: 300px !important;
  height: 300px !important;
}
</style>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElDatePicker, ElTimePicker } from 'element-plus'

// 获取今天日期
function getToday() {
  const d = new Date()
  return d.toISOString().slice(0, 10)
}

// 格式化日期为 YYYY-MM-DD
function formatDateToYMD(val) {
  if (val instanceof Date) {
    const year = val.getFullYear();
    const month = String(val.getMonth() + 1).padStart(2, '0');
    const day = String(val.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } else if (typeof val === 'string' && val.includes('T')) {
    return val.slice(0, 10);
  } else if (typeof val === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(val)) {
    return val;
  } else {
    try {
      const dateObj = new Date(val);
      const year = dateObj.getFullYear();
      const month = String(dateObj.getMonth() + 1).padStart(2, '0');
      const day = String(dateObj.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    } catch {
      return '';
    }
  }
}

// 数据
const date = ref(getToday())
const time = ref('12:00:00')
const thing = ref('')
const list = ref([])
let id = 0

// 编辑相关
const editDialogVisible = ref(false)
const editForm = ref({
  id: null,
  date: '',
  time: '',
  thing: ''
})
const originalEditItem = ref(null) // 保存原始数据用于撤销

// 添加事项
function addThing() {
  // 输入校验
  if (!thing.value.trim()) {
    ElMessage.warning('请输入事项内容');
    return;
  }
  if (!date.value) {
    ElMessage.warning('请选择日期');
    return;
  }
  if (!time.value) {
    ElMessage.warning('请选择时间');
    return;
  }
  
  const dateStr = formatDateToYMD(date.value)
  const newItem = {
    id: id++,
    date: dateStr,
    time: time.value,
    thing: thing.value,
    done: false
  }
  
  list.value.push(newItem)
  thing.value = ''
  time.value = '12:00:00' // 重置时间
  ElMessage.success('添加成功')
}

// 切换事项状态
function toggleDone(item) {
  item.done = !item.done;
  ElMessage.success(item.done ? '已标记为已做' : '已标记为未做');
}

// 开始编辑事项
function startEdit(item) {
  // 保存原始数据
  originalEditItem.value = { ...item }
  
  // 复制数据到编辑表单
  editForm.value = {
    id: item.id,
    date: item.date,
    time: item.time,
    thing: item.thing
  }
  
  // 显示编辑弹窗
  editDialogVisible.value = true
}

// 保存编辑
function saveEdit() {
  // 输入校验
  if (!editForm.value.thing.trim()) {
    ElMessage.warning('请输入事项内容');
    return;
  }
  if (!editForm.value.date) {
    ElMessage.warning('请选择日期');
    return;
  }
  if (!editForm.value.time) {
    ElMessage.warning('请选择时间');
    return;
  }
  
  // 更新列表中的数据
  const index = list.value.findIndex(i => i.id === editForm.value.id)
  if (index !== -1) {
    list.value.splice(index, 1, {
      ...editForm.value,
      done: list.value[index].done // 保留原状态
    })
    ElMessage.success('修改成功')
  }
  
  editDialogVisible.value = false
}

// 确认删除
function confirmDelete(item) {
  ElMessage.confirm('确定要删除该事项吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteThing(item)
  }).catch(() => {
    // 取消操作
  })
}

// 删除事项
function deleteThing(item) {
  const index = list.value.findIndex(i => i.id === item.id)
  if (index !== -1) {
    list.value.splice(index, 1)
    ElMessage.success('删除成功')
  }
}

// 计算属性：今天的事项
const todayList = computed(() => {
  const today = formatDateToYMD(getToday())
  return list.value.filter(item => formatDateToYMD(item.date) === today)
})

// 计算属性：未来的事项
const futureList = computed(() => {
  const today = formatDateToYMD(getToday())
  return list.value.filter(item => formatDateToYMD(item.date) > today).sort((a, b) => formatDateToYMD(a.date).localeCompare(formatDateToYMD(b.date)))
})

// 监听编辑弹窗关闭，恢复原始数据
watch(editDialogVisible, (val) => {
  if (!val && originalEditItem.value) {
    // 如果用户取消编辑，恢复原始数据
    const index = list.value.findIndex(i => i.id === originalEditItem.value.id)
    if (index !== -1) {
      list.value.splice(index, 1, originalEditItem.value)
    }
    originalEditItem.value = null
  }
})
</script>